import {router} from "./index";
import Router from "vue-router";
import { getToken, removeToken } from "@/utils/cookie";
import { Message } from "element-ui";
import store from "@/store";
// 修复router莫名其妙报错
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => err);
};
// 路由守卫
router.beforeEach((to, from, next) => {
  //不需要验证登录
  if (to.meta.noLogin) {
    //退出时清除token
    if (to.path === "/login") {
      removeToken();
      store.commit("SET_TOKEN", "");
      store.commit('CLEAR_MAINTABS');
      store.commit('SET_ACTIVETAB','');
    }
    next();
  } else {
    if (getToken()) {
      setTabs(to);
      next();
    } else {
      Message.error({
        message: "用户认证失败，请重新登录!"
      });
      next("/login");
    }
  }
});
//添加tab标签
function setTabs(to) {
  if (to.meta.isMenu) {
    let mainTabs = store.state.app.mainTabs;
    if (!mainTabs.find(item => item.name === to.name)) {
      store.commit("PUSH_MAINTABS", { title: to.meta.name, name: to.name });
    }
    store.commit("SET_ACTIVETAB", to.name);
  }
}
